/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufg.inf.si.poo.formula1.GUI;

import br.ufg.inf.si.poo.formula1.Circuit.Circuit;
import br.ufg.inf.si.poo.formula1.Driver.Driver;
import br.ufg.inf.si.poo.formula1.Library.Library;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFiles;
import br.ufg.inf.si.poo.formula1.Season.Season;
import br.ufg.inf.si.poo.formula1.Team.Team;
import java.util.ArrayList;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

/**
 * FrameMain
 *
 * Versao 1.0
 *
 * Data 16/02/2013
 *
 * @author Igor
 */
public class FrameMain extends javax.swing.JFrame {
    //Atributos
    private static ArrayList<Season> seasons = null;
    private static ArrayList<Team> teams = null;
    private static ArrayList<Circuit> circuits = null;
    private static ArrayList<Driver> drivers = null;
    private static Season seasonLoaded = null;
    private static String folderSeasonLoaded = "";
    
    private RegisterSeason registerSeason = null;
    private RegisterTeam registerTeam = null;
    private RegisterDriver registerDriver = null;
    private RegisterCircuit registerCircuit = null;
    private ManageTeamsSeason manageTeamsSeason = null;
    private ManageRaceSeason manageRaceSeason = null;
    private ReportSeason reportSeason = null;

    //Construtores
    /**
     * Creates new form FrameMain
     */
    public FrameMain() {
        initComponents();

        FrameMain.seasons = new ArrayList();
        FrameMain.teams = new ArrayList();
        FrameMain.circuits = new ArrayList();
        FrameMain.drivers = new ArrayList();
        FrameMain.seasonLoaded = null;
        
        this.registerSeason = null;
        this.registerTeam = null;
        this.registerDriver = null;
        this.registerCircuit = null;
        this.manageTeamsSeason = null;
        this.manageRaceSeason = null;
        this.reportSeason = null;
        
        ManagementFiles.readDriver(this.drivers);
        ManagementFiles.readTeam(this.teams);
        ManagementFiles.readCircuit(this.circuits);
        ManagementFiles.readSeason(this.seasons);

        Library.centralizarFrameOrInternalFrame(this, null, null);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    
    

    //Metodos Getters e Setters
    /**
     * Retorna o abtributo ArrayList season (ArryList de temporadas)
     * @return the season
     */
    public static ArrayList<Season> getSeasons() {
        return seasons;
    }

    /**
     * Altera o abtributo ArrayList season (adiciona season por season ao ArrayList)
     * @param season the season to set
     */
    public static void setSeasons(Season season) {
        FrameMain.seasons.add(season);
    }

    /**
     * Retorna o atributo ArrayList team (ArrayList de equipes)
     * @return the team
     */
    public static ArrayList<Team> getTeams() {
        return FrameMain.teams;
    }

    /**
     * Altera o abtributo ArrayList team (adiciona team por team ao ArrayList)
     * @param team the team to set
     */
    public static void setTeams(Team team) {
        FrameMain.teams.add(team);
    }

    /**
     * Retorna o atributo ArrayList circuit (ArrayList de circuitos)
     * @return the circuit
     */
    public static ArrayList<Circuit> getCircuits() {
        return FrameMain.circuits;
    }

    /**
     * Altera o abtributo ArrayList circuit (adiciona circuit por circuit ao ArrayList)
     * @param circuit the circuit to set
     */
    public static void setCircuits(Circuit circuit) {
        FrameMain.circuits.add(circuit);
    }

    /**
     * Retorna o atributo ArrayList driver (ArrayList de pilotos)
     * @return the driver
     */
    public static ArrayList<Driver> getDrivers() {
        return FrameMain.drivers;
    }

    /**
     * Altera o abtributo ArrayList driver (adiciona driver por driver ao ArrayList)
     * @param driver the driver to set
     */
    public static void setDrivers(Driver driver) {
        FrameMain.drivers.add(driver);
    }

    /**
     * Retorna o atributo seasonLoaded (referente aa temporada carregada do arquivo)
     * @return the seasonLoaded
     */
    public static Season getSeasonLoaded() {
        return FrameMain.seasonLoaded;
    }

    /**
     * Altera o atributo seasonLoaded (referente aa temporada carregada do arquivo)
     * @param aSeasonLoaded the seasonLoaded to set
     */
    public static void setSeasonLoaded(Season seasonLoaded) {
        FrameMain.seasonLoaded = seasonLoaded;
        FrameMain.folderSeasonLoaded = "./Arquivos/Texto/Temporadas/"+FrameMain.seasonLoaded.getYear()+"/";
    }

    /**
     * Retorna o endereco da pasta da temporada
     * @return the folderSeasonLoaded
     */
    public static String getFolderSeasonLoaded() {
        return folderSeasonLoaded;
    }

    //Outros Metodos
    /**
     * Exibe no DesktopPane os InternalFrames 
     * @param internalFrame frame a ser exibido no DesktopPane
     */
    private void displayInternalFrame(JInternalFrame internalFrame){
        //Adiciona ao desktopPane caso nao tenha sido adicionado ou foi fechado na ultima vez
        if(!checkInternalFramesOpen(this.desktopPanePapelDeParede, internalFrame)){
            this.desktopPanePapelDeParede.add(internalFrame);
        }
        
        // Garante que nao é um icone  
        try {
            if (internalFrame.isIcon()) {
                internalFrame.setIcon(false);
            }
        } catch (java.beans.PropertyVetoException e) {
            //tratar erro  
        }

        Library.centralizarFrameOrInternalFrame(this, this.desktopPanePapelDeParede, internalFrame);
        internalFrame.setVisible(true);
    }

     /** 
      * Metodo que faz a verificacao se o JInternalFrame foi instaciado no DektopPane
      * @param jDesktopPane jDesktopPane da aplicação 
      * @param frame Frame a ser verificado 
      * @return valor True se o Frame estiver instanciado 
      */  
    //construtor recebe o JDesktopPane e o JInternalFrame que deseja verififcar 
    private Boolean checkInternalFramesOpen(JDesktopPane jDesktopPane, JInternalFrame internalFrame) {
        for (int i = 0; i < jDesktopPane.getAllFrames().length; i++) {
            if (jDesktopPane.getAllFrames()[i].equals(internalFrame)) {  //se o internalFrame pesquisado estiver na tela, retornar true  
                return true;
            }
        }
        return false;
    }  
    
    /**
     * Verifica se uma temporada foi carregada ou nao
     * @return verdadei ou falso se uma temporada foi carregada
     */
    private Boolean checkSeasonLoaded(){
        if(FrameMain.seasonLoaded == null){
            return false;
        }
        return true;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelPapelDeParede = new javax.swing.JPanel();
        desktopPanePapelDeParede = new javax.swing.JDesktopPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuGerenciar = new javax.swing.JMenu();
        menuGerenciarCircuitos = new javax.swing.JMenuItem();
        menuGerenciarEquipes = new javax.swing.JMenuItem();
        menuGerenciarPilotos = new javax.swing.JMenuItem();
        menuGerenciarTemporadas = new javax.swing.JMenuItem();
        menuTemporada = new javax.swing.JMenu();
        menuTemporadaEquipes = new javax.swing.JMenuItem();
        menuTemporadaCorridas = new javax.swing.JMenuItem();
        menuTemporadaRelatorios = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("GUI - Formula 1 Simulator");

        desktopPanePapelDeParede.setToolTipText("");
        desktopPanePapelDeParede.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        desktopPanePapelDeParede.setName(""); // NOI18N

        javax.swing.GroupLayout panelPapelDeParedeLayout = new javax.swing.GroupLayout(panelPapelDeParede);
        panelPapelDeParede.setLayout(panelPapelDeParedeLayout);
        panelPapelDeParedeLayout.setHorizontalGroup(
            panelPapelDeParedeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPanePapelDeParede, javax.swing.GroupLayout.DEFAULT_SIZE, 1040, Short.MAX_VALUE)
        );
        panelPapelDeParedeLayout.setVerticalGroup(
            panelPapelDeParedeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPanePapelDeParede, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
        );

        menuGerenciar.setText("Gerenciar");

        menuGerenciarCircuitos.setText("Circuitos");
        menuGerenciarCircuitos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarCircuitosActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarCircuitos);

        menuGerenciarEquipes.setText("Equipes");
        menuGerenciarEquipes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarEquipesActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarEquipes);

        menuGerenciarPilotos.setText("Pilotos");
        menuGerenciarPilotos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarPilotosActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarPilotos);

        menuGerenciarTemporadas.setText("Temporadas");
        menuGerenciarTemporadas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGerenciarTemporadasActionPerformed(evt);
            }
        });
        menuGerenciar.add(menuGerenciarTemporadas);

        jMenuBar1.add(menuGerenciar);

        menuTemporada.setText("Temporada");

        menuTemporadaEquipes.setText("Equipes");
        menuTemporadaEquipes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTemporadaEquipesActionPerformed(evt);
            }
        });
        menuTemporada.add(menuTemporadaEquipes);

        menuTemporadaCorridas.setText("Corridas");
        menuTemporadaCorridas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTemporadaCorridasActionPerformed(evt);
            }
        });
        menuTemporada.add(menuTemporadaCorridas);

        menuTemporadaRelatorios.setText("Relatórios");
        menuTemporadaRelatorios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTemporadaRelatoriosActionPerformed(evt);
            }
        });
        menuTemporada.add(menuTemporadaRelatorios);

        jMenuBar1.add(menuTemporada);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelPapelDeParede, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelPapelDeParede, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        getAccessibleContext().setAccessibleDescription("GUI - Formula 1 Simulator");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuGerenciarEquipesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarEquipesActionPerformed
        //Instancia o Objeto se nao foi instanciado
        if(this.registerTeam == null){
            this.registerTeam = new RegisterTeam();
        }
        displayInternalFrame(this.registerTeam);
    }//GEN-LAST:event_menuGerenciarEquipesActionPerformed

    private void menuGerenciarPilotosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarPilotosActionPerformed
        //Instancia o Objeto se nao foi instanciado
        if(this.registerDriver == null){
            this.registerDriver = new RegisterDriver();
        }
        displayInternalFrame(this.registerDriver);
    }//GEN-LAST:event_menuGerenciarPilotosActionPerformed

    private void menuGerenciarCircuitosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarCircuitosActionPerformed
        //Instancia o Objeto se nao foi instanciado
        if(this.registerCircuit == null){
            this.registerCircuit = new RegisterCircuit();
        }
        displayInternalFrame(this.registerCircuit);
    }//GEN-LAST:event_menuGerenciarCircuitosActionPerformed

    private void menuGerenciarTemporadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGerenciarTemporadasActionPerformed
        //Instancia o Objeto se nao foi instanciado
        if(this.registerSeason == null){
            this.registerSeason = new RegisterSeason();
        }
        displayInternalFrame(this.registerSeason);
    }//GEN-LAST:event_menuGerenciarTemporadasActionPerformed

    private void menuTemporadaEquipesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTemporadaEquipesActionPerformed
        // TODO add your handling code here:
        if(checkSeasonLoaded()){
            if(this.manageTeamsSeason == null){
                this.manageTeamsSeason = new ManageTeamsSeason();
            }
            displayInternalFrame(this.manageTeamsSeason);
        }else{
            JOptionPane.showMessageDialog(this, "Carregue os dados de uma temporada!"+
                                                "\nMenu Gerenciar -> Temporadas"+
                                                "\nSelecione uma temporada e cleque em 'Carregar  Temporada'"
                                           , "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuTemporadaEquipesActionPerformed

    private void menuTemporadaCorridasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTemporadaCorridasActionPerformed
        // TODO add your handling code here:
        if(checkSeasonLoaded()){
            if(this.manageRaceSeason == null){
                this.manageRaceSeason = new ManageRaceSeason();
            }
            displayInternalFrame(this.manageRaceSeason);
        }else{
            JOptionPane.showMessageDialog(this, "Carregue os dados de uma temporada!"+
                                                "\nMenu Gerenciar -> Temporadas"+
                                                "\nSelecione uma temporada e cleque em 'Carregar  Temporada'"
                                           , "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuTemporadaCorridasActionPerformed

    private void menuTemporadaRelatoriosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTemporadaRelatoriosActionPerformed
        // TODO add your handling code here:
        if(checkSeasonLoaded()){
            if(this.reportSeason == null){
                this.reportSeason = new ReportSeason();
            }
            displayInternalFrame(this.reportSeason);
        }else{
            JOptionPane.showMessageDialog(this, "Carregue os dados de uma temporada!"+
                                                "\nMenu Gerenciar -> Temporadas"+
                                                "\nSelecione uma temporada e cleque em 'Carregar  Temporada'"
                                           , "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuTemporadaRelatoriosActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrameMain().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDesktopPane desktopPanePapelDeParede;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu menuGerenciar;
    private javax.swing.JMenuItem menuGerenciarCircuitos;
    private javax.swing.JMenuItem menuGerenciarEquipes;
    private javax.swing.JMenuItem menuGerenciarPilotos;
    private javax.swing.JMenuItem menuGerenciarTemporadas;
    private javax.swing.JMenu menuTemporada;
    private javax.swing.JMenuItem menuTemporadaCorridas;
    private javax.swing.JMenuItem menuTemporadaEquipes;
    private javax.swing.JMenuItem menuTemporadaRelatorios;
    private javax.swing.JPanel panelPapelDeParede;
    // End of variables declaration//GEN-END:variables

}
